package com.zeyi.chat.handler;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.controller.ChatInfoController;
import com.zeyi.chat.controller.HomeController;
import com.zeyi.chat.dto.Chat;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.manager.StageManager;
import com.zeyi.chat.manager.UserManager;
import com.zeyi.chat.po.ChatGroup;
import com.zeyi.chat.po.User;
import com.zeyi.chat.utils.AvatarUtil;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zeyi
 */
public class ChatHandler {

    private ChatHandler() {
    }

    private static class Singleton {
        public static final ChatHandler INSTANCE = new ChatHandler();
    }

    public static ChatHandler getInstance() {
        return ChatHandler.Singleton.INSTANCE;
    }

    /**
     * 处理用户信息更新
     */
    @Mapping("userInfo")
    public void handleUserInfo(Message message) {
        User user = JSON.parseObject(message.getData(), User.class);
        Platform.runLater(() -> ChatInfoController.getInstance().displayUserInfo(user, false));
    }

    /**
     * 处理群信息更新
     */
    @Mapping("groupInfo")
    public void handleGroupInfo(Message message) {
        ChatGroup group = JSON.parseObject(message.getData(), ChatGroup.class);
        Platform.runLater(() -> ChatInfoController.getInstance().displayGroupInfo(group,
                group.getCreateId()==UserManager.getCurrentUser().getId()));
    }

    /**
     * 处理删除聊天
     */
    @Mapping("deleteChat")
    public void handleDelete(Message message) {
        Map<String, Integer> map = JSON.parseObject(message.getData(), Map.class);
        Integer type = map.get("type");
        Integer id = map.get("deleteId");
        List<Chat> list = UserManager.getCurrentUser().getChatList();
        List<Chat> collect;
        if (type == 0) {
            collect = list.stream().filter(chat -> chat.getCreateId() != null || !chat.getId().equals(id)).collect(Collectors.toList());
        } else {
            collect = list.stream().filter(chat -> chat.getCreateId() == null || !chat.getId().equals(id)).collect(Collectors.toList());
        }
        UserManager.getCurrentUser().setChatList(collect);
        Platform.runLater(() -> {
            Stage primaryStage = StageManager.getPrimaryStage();
            ListView<Chat> chatList = (ListView<Chat>) primaryStage.getScene().getRoot().lookup("#chatList");
            chatList.setItems(FXCollections.observableArrayList(collect));
            String chatName = type == 0 ? "private" : "group";
            chatName += id;
            Pane chat = StageManager.getChat(chatName);
            StageManager.removeChat(chatName);
            Pane chatContainer = (Pane) primaryStage.getScene().getRoot().lookup("#chatContainer");
            if (chatContainer == chat) {
                Pane wrapContainer = (Pane) primaryStage.getScene().getRoot().lookup("#wrapContainer");
                Pane chatAreaTop = (Pane) primaryStage.getScene().getRoot().lookup("#chatAreaTop");
                chatAreaTop.setVisible(false);
                wrapContainer.getChildren().clear();
                Pane pane = new Pane();
                pane.setPrefWidth(695);
                pane.setPrefHeight(690);
                Label label = new Label("找人聊聊天吧");
                label.setFont(new Font("Yu Gothic UI Semilight", 30));
                label.setTextFill(Paint.valueOf("#909399"));
                label.setLayoutX(258);
                label.setLayoutY(279);
                pane.getChildren().add(label);
                wrapContainer.getChildren().add(pane);
            }
        });
    }

    /**
     * 处理私聊信息
     */
    @Mapping("chatPrivate")
    public void handlePrivate(Message message) {
        User sender = message.getSender();
        String chatId = "private" + sender.getId();
        Platform.runLater(() -> {
            HomeController.getInstance().displayChat(chatId, sender, message.getData(), "0");
        });
    }

    /**
     * 处理群聊
     */
    @Mapping("chatGroup")
    public void handleGroup(Message message) {
        User sender = message.getSender();
        String chatId = "group" + message.getReceiver().getId();
        Platform.runLater(() -> {
            HomeController.getInstance().displayChat(chatId, sender, message.getData(), "1");
        });
    }

    /**
     * 处理获取的群成员
     */
    @Mapping("getGroupMember")
    public void handleGroupMember(Message message) {
        ChatGroup group = JSON.parseObject(message.getData(), ChatGroup.class);
        Platform.runLater(() -> {
            HomeController.getInstance().displayGroupMember(group);
        });
    }

    /**
     * 处理在线状态
     */
    @Mapping("online")
    public void handleOnline(Message message) {
        Chat chat = JSON.parseObject(message.getData(), Chat.class);
        Platform.runLater(() -> {
            Stage primaryStage = StageManager.getPrimaryStage();
            ImageView avatar = ((ImageView) primaryStage.getScene().getRoot().lookup("#chatList")
                    .lookup("#private" + chat.getId()).lookup("#chatAvatar"));
            List<Chat> chatList = UserManager.getCurrentUser().getChatList();
            for (int i = 0; i < chatList.size(); i++) {
                Chat chat1 = chatList.get(i);
                if (chat1.getCreateId() == null && chat1.getId() == chat.getId()) {
                    chat1.setIsOnline(true);
                }
            }
            if (chat.getIsOnline()) {
                avatar.setImage(new Image(AvatarUtil.suffix + chat.getAvatar(), 50, 50, false, true));
            } else {
                avatar.setImage(new Image("/images/avatar/offline.png", 50, 50, false, true));
            }
        });
    }
}
